import json
import requests
import time
from conf.config import Max,Type,ClassFicationCode,Px
def DLCSV():
    try:
        with open('./cache/{0}/cache.json'.format(ClassFicationCode),'r') as f:
            RDict=json.load(fp=f)
        with open('./cache/{0}/cache.json'.format(ClassFicationCode),'r') as f:
            Record=json.load(fp=f)
    except Exception as e:
        with open('./cache/{0}/cache1.json'.format(ClassFicationCode),'r') as f:
            RDict=json.load(fp=f)
        with open('./cache/{0}/cache1.json'.format(ClassFicationCode),'r') as f:
            Record=json.load(fp=f)
    for i in RDict.keys():
        for j in RDict.get(i).get(list(RDict.get(i).keys())[0]):
            t = 1
            while t == 1:
                t = 0
                print('enter')
                try:
                    url = ("https://comtrade.un.org/api/get?max={0}&type={1}&freq=A&px={2}&ps={3}&r={4}&p=all&rg=all&cc={5}&fmt=csv".format(Max,Type,Px,j,i,ClassFicationCode))
                    filename = ("./cache/{0}/{1}-{2}.csv".format(ClassFicationCode,list(RDict.get(i).keys())[0],j))
                    res = requests.get(url)
                    if res.status_code!=200:
                        t=1
                        continue
                    with open(filename,'wb') as fp:
                        fp.write(res.content)
                    print(list(RDict.get(i).keys())[0],j)
                except Exception as e:
                    print(e)
                    print("reget")
                    t = 1
            print('exit')
            Record.get(i).get(list(Record.get(i).keys())[0]).remove(j)
            with open('./cache/{0}/cache.json'.format(ClassFicationCode),'w') as f:
                f.write(json.dumps(Record,indent=4))
            with open('./cache/{0}/cache1.json'.format(ClassFicationCode),'w') as f:
                f.write(json.dumps(Record,indent=4))
            with open('./cache/{0}/cache.json'.format(ClassFicationCode),'r') as f:
                Record = json.load(fp=f)
            time.sleep(36)